package org.example;

import java.io.InputStream;
import java.sql.*;
import java.util.List;
import java.util.Properties;

public class DatabaseManager {
    private static String DB_URL;
    private static String DB_USER;
    private static String DB_PASSWORD;
    
    // 静态初始化块，从配置文件加载数据库配置
    static {
        Properties prop = new Properties();
        try (InputStream input = DatabaseManager.class.getClassLoader().getResourceAsStream("application.properties")) {
            if (input != null) {
                prop.load(input);
                DB_URL = prop.getProperty("db.url", "jdbc:h2:~/logparser;AUTO_SERVER=TRUE");
                DB_USER = prop.getProperty("db.user", "sa");
                DB_PASSWORD = prop.getProperty("db.password", "");
            } else {
                // 如果配置文件不存在，使用默认配置
                DB_URL = "jdbc:h2:~/logparser;AUTO_SERVER=TRUE";
                DB_USER = "sa";
                DB_PASSWORD = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 如果配置文件加载失败，使用默认配置
            DB_URL = "jdbc:h2:~/logparser;AUTO_SERVER=TRUE";
            DB_USER = "sa";
            DB_PASSWORD = "";
        }
    }

    // 初始化数据库表
    public static void initializeDatabase() throws SQLException {
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            // 删除原有的表（如果存在）
            String dropTableSQL = "DROP TABLE IF EXISTS log_info";
            try (Statement stmt = conn.createStatement()) {
                stmt.execute(dropTableSQL);
            }

            // 创建新的表
            String createTableSQL = "CREATE TABLE log_info (" +
                    "id BIGINT AUTO_INCREMENT PRIMARY KEY, " +
                    "query VARCHAR(255), " +
                    "log_id VARCHAR(255), " +
                    "user_id VARCHAR(255), " +
                    "message_id VARCHAR(255), " +
                    "domain_id VARCHAR(255), " +
                    "subject_id VARCHAR(255), " +
                    "processor VARCHAR(255), " +
                    "request TEXT, " +
                    "response TEXT, " +
                    "elapsed_time VARCHAR(50), " +
                    "log_time VARCHAR(50)" +
                    ")";

            try (Statement stmt = conn.createStatement()) {
                stmt.execute(createTableSQL);
            }
        }
    }

    // 插入日志信息到数据库
    public static void insertLogInfo(LogParserApp.LogPO logInfo) throws SQLException {
        String insertSQL = "INSERT INTO log_info (query, log_id, user_id, message_id, domain_id, subject_id, processor, request, response, elapsed_time, log_time) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(insertSQL)) {
            
            pstmt.setString(1, logInfo.getQuery());
            pstmt.setString(2, logInfo.getLogId());
            pstmt.setString(3, logInfo.getUserId());
            pstmt.setString(4, logInfo.getMessageId());
            pstmt.setString(5, logInfo.getDomainId());
            pstmt.setString(6, logInfo.getSubjectId());
            pstmt.setString(7, logInfo.getProcessor());
            pstmt.setString(8, logInfo.getRequest());
            pstmt.setString(9, logInfo.getResponse());
            pstmt.setString(10, logInfo.getElapsed_time());
            pstmt.setString(11, logInfo.getLog_time());

            pstmt.executeUpdate();
        }
    }

    // 获取数据库连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
    }
    
    // 批量插入日志信息到数据库
    public static void batchInsertLogInfo(List<LogParserApp.LogPO> logInfos) throws SQLException {
        String insertSQL = "INSERT INTO log_info (query, log_id, user_id, message_id, domain_id, subject_id, processor, request, response, elapsed_time, log_time) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(insertSQL)) {
            
            // 关闭自动提交
            conn.setAutoCommit(false);
            
            for (LogParserApp.LogPO logInfo : logInfos) {
                pstmt.setString(1, logInfo.getQuery());
                pstmt.setString(2, logInfo.getLogId());
                pstmt.setString(3, logInfo.getUserId());
                pstmt.setString(4, logInfo.getMessageId());
                pstmt.setString(5, logInfo.getDomainId());
                pstmt.setString(6, logInfo.getSubjectId());
                pstmt.setString(7, logInfo.getProcessor());
                pstmt.setString(8, logInfo.getRequest());
                pstmt.setString(9, logInfo.getResponse());
                pstmt.setString(10, logInfo.getElapsed_time());
                pstmt.setString(11, logInfo.getLog_time());
                
                pstmt.addBatch();
            }
            
            // 执行批量插入
            pstmt.executeBatch();
            
            // 提交事务
            conn.commit();
            
            // 恢复自动提交
            conn.setAutoCommit(true);
        } catch (SQLException e) {
            // 发生异常时回滚事务
            throw e;
        }
    }
    
    // 执行SQL查询
    public static ResultSet executeQuery(String sql) throws SQLException {
        Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
        Statement stmt = conn.createStatement();
        return stmt.executeQuery(sql);
    }
}